import axios from "axios";
class Jdrequest {
  constructor(config) {
    this.instance = axios.create(config);
    this.interceptor = config.interceptor;
    // 调用请求拦截器
    this.instance.interceptors.request.use(
      this.interceptor?.requestInterceptor,
      this.interceptor?.requestInterceptorCatch
    );

    // 调用响应拦截器
    this.instance.interceptors.response.use(
      this.interceptor?.responseInterceptor,
      this.interceptor?.responseInterceptorCatch
    );
  }
  request(config) {
    return new Promise((resolve, reject) => {
      if (config.interceptor?.requestInterceptor) {
        config = config.interceptor.requestInterceptor(config);
      }
      this.instance
        .request(config)
        .then((res) => {
          if (config.interceptor?.responseInterceptor) {
            res = config.interceptor.responseInterceptor(res);
          }
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  }
  post(params) {
    return this.request({ ...params, method: "POST" });
  }
  get(params) {
    return this.request({ ...params, method: "GET" });
  }
}
export default Jdrequest;
